<template>
  <div class="editor">
    <Editor
     v-model="content"
     api-key="200nnt2lqfelk1e83jnrxsdozh8axk269pwm4xlgxo5mduhi"
     :init="{
      toolbar_mode: 'sliding',
      plugins: ['image'],
      toolbar: 'image',
      min_height: 700,
      images_upload_handler: images_upload_handler
     }"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue'
import Editor from '@tinymce/tinymce-vue'
import axios from 'axios'
import { useUserStore } from '@/store/modules/user'


let props = defineProps({
  modelValue: String,
})

let imgServer = ref(import.meta.env.VITE_IMG_SERVE)

const userStore = useUserStore()
let $emit = defineEmits(['update:modelValue'])
const images_upload_handler = async (blobInfo, progress) => {
    var formData;
    var file = blobInfo.blob();//转化为易于理解的file对象
    formData = new FormData();
    formData.append('files', file, file.name );//此处与源文档不一样
    

    let istance =axios.create({
        baseURL: import.meta.env.VITE_APP_BASE_API,
        timeout: 5000, // 超时时间
        withCredentials: true,
        headers: {
            'Content-Type': 'multipart/form-data',
            'Access-Token': userStore.token
        },
    })

    return new Promise(async (resolve, reject) => {
        try {
            let { status, data, message } = await istance.post('/upload', formData)
            if (status == 200) {
                let url = imgServer.value + data?.data[0]?.fileUrl
                resolve(url);
            } else {
                reject(message)
            }
        } catch (error) {
            reject('HTTP Error: ' + error);
        }

    })
}

let content = ref('')

let timer = null
watch(() => content.value, (val) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
        $emit('update:modelValue', val)
    }, 500)
})

watch(() => props.modelValue, (val) => {
    if (val) {
        content.value = val
    }
})
</script>

<style scoped>
.editor {
    width: 100%;
    height: 100%;
}
</style>
